﻿using Frp客户端.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.IO;

namespace Frp客户端
{
    public partial class FrpTool : Form
    {
        public int type = 0;
        public int log = 0;
        public string rootDirectory = "";
        FrpsConfig config = new FrpsConfig();
        private FileSystemWatcher fileWatcher;
        public FrpTool()
        {
            InitializeComponent();
            ReadConfigFile();
            //获取根目录
            rootDirectory = AppDomain.CurrentDomain.BaseDirectory;
            RedConfig();
            getIpAsync();
            StartWatchingFile();
            ReadAndDisplayLogs();
        }

        /// <summary>
        /// 读取frp配置
        /// </summary>
        public void RedConfig()
        {
            if (type == 0)
            {
                string jsonFilePath = rootDirectory + "\\frp\\frps.json";
                // 判断文件是否存在
                if (File.Exists(jsonFilePath))
                {
                    try
                    {
                        string jsonContent = File.ReadAllText(jsonFilePath);
                        // 反序列化JSON内容到RootConfig对象
                        config = JsonConvert.DeserializeObject<FrpsConfig>(jsonContent);
                        bindPort.Text = config.bindPort.ToString();
                        token.Text = config.auth.token;
                        to.Text = config.log.to;
                        level.Text = config.log.level;
                        maxDays.Value = config.log.maxDays;
                        addr.Text = config.webServer.addr;
                        port.Text = config.webServer.port.ToString();
                        user.Text = config.webServer.user;
                        password.Text = config.webServer.password;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"读取JSON文件出错: {ex.Message}");
                    }
                }
                else
                {
                    MessageBox.Show("指定的JSON文件不存在。");
                }
            }
            else
            {
                string jsonFilePath = rootDirectory + "\\frp\\frpc.json";
                // 判断文件是否存在
                if (File.Exists(jsonFilePath))
                {
                    try
                    {
                        string jsonContent = File.ReadAllText(jsonFilePath);
                        // 反序列化JSON内容到RootConfig对象
                        FrpcConfig config = JsonConvert.DeserializeObject<FrpcConfig>(jsonContent);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"读取JSON文件出错: {ex.Message}");
                    }
                }
                else
                {
                    MessageBox.Show("指定的JSON文件不存在。");
                }
            }



        }
        /// <summary>
        /// 读取当前配置
        /// </summary>
        public void ReadConfigFile()
        {
            string configFilePath = Path.Combine(rootDirectory, "config.txt");
            try
            {
                using (StreamReader reader = new StreamReader(configFilePath))
                {
                    string fileContent = reader.ReadToEnd();
                    type = int.Parse(fileContent);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred: " + e.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //SaveFrps();
            StartFrpsProcess0();
        }
        public void StartFrpsProcess0()
        {
            try
            {
                Process process = new Process();
                // 设置要启动的进程的文件名，这里使用相对路径指向frp文件夹下的frpc.exe
                process.StartInfo.FileName = @".\frp\frps.exe";
                // 设置命令行参数，对应 -c.\client.ini
                process.StartInfo.Arguments = @"-c.\frp\frps.json";
                // 设置工作目录为包含frp文件夹的当前目录（这样相对路径才能正确指向对应的exe和ini文件）
                process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
                // 配置窗口样式等，以下配置为隐藏命令行窗口，如果你希望显示窗口可以根据需要调整
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow = true;
                // 启动进程
                process.Start();
                MessageBox.Show("Frp客户端已启动！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动Frp客户端失败！" + ex.Message);
            }

        }
        #region frps服务端
        public void SaveFrps()
        {
            string jsonFilePath = rootDirectory + "\\frp\\frps.json";
            File.WriteAllText(jsonFilePath, JsonConvert.SerializeObject(config, Formatting.Indented));

            RedConfig();
        }

        private void bindPort_TextChanged(object sender, EventArgs e)
        {
            config.bindPort = int.Parse(bindPort.Text);
            SaveFrps();
        }

        private void token_TextChanged(object sender, EventArgs e)
        {
            config.auth.token = token.Text;
            SaveFrps();
        }

        private void to_TextChanged(object sender, EventArgs e)
        {
            config.log.to = to.Text;
            SaveFrps();
        }

        private void addr_TextChanged(object sender, EventArgs e)
        {
            config.webServer.addr = addr.Text;
            SaveFrps();
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            config.webServer.port = int.Parse(port.Text);
            SaveFrps();
        }

        private void user_TextChanged(object sender, EventArgs e)
        {
            config.webServer.user = user.Text;
            SaveFrps();
        }

        private void password_TextChanged(object sender, EventArgs e)
        {
            config.webServer.password = password.Text;
            SaveFrps();
        }

        private void level_SelectedIndexChanged(object sender, EventArgs e)
        {
            config.log.level = level.Text;
            SaveFrps();
        }

        private void maxDays_ValueChanged(object sender, EventArgs e)
        {
            config.log.maxDays = int.Parse(maxDays.Value.ToString());
            SaveFrps();
        } 
        #endregion
        public async Task getIpAsync()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    this.ip.Text = "当前ip:     " + ip.ToString();
                    Console.WriteLine("本地IP地址: " + ip.ToString());
                }
            }
            //var ec2Client = new AmazonEC2Client();
            //try
            //{
            //    var request = new DescribeInstancesRequest();
            //    var response = await ec2Client.DescribeInstancesAsync(request);
            //    foreach (var reservation in response.Reservations)
            //    {
            //        foreach (var instance in reservation.Instances)
            //        {
            //            if (instance.PublicIpAddress != null)
            //            {
            //                Console.WriteLine("公网IP: " + instance.PublicIpAddress);
            //            }
            //            this.ip.Text = "当前ip:     " + instance.PublicIpAddress;
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("获取公网IP出错: " + ex.Message);
            //}
        }
        private void ReadAndDisplayLogs()
        {
            string logFilePath = rootDirectory + "\\frp\\log\\frpslog.log";
            try
            {
                if (File.Exists(logFilePath))
                {
                    string[] logLines = File.ReadAllLines(logFilePath);
                    if (log==0)
                    {
                        foreach (string line in logLines)
                        {
                            richTextBox1.AppendText(line + Environment.NewLine);
                        }
                        log = 1;
                    }
                    else
                    {
                        richTextBox1.AppendText(logLines[logLines.Length-1] + Environment.NewLine);
                    }
                    
                    // 将光标定位到文本框最后，以实现滚动效果，让最后一行日志可见
                    richTextBox1.SelectionStart = richTextBox1.Text.Length;
                    richTextBox1.ScrollToCaret();
                }
                else
                {
                    MessageBox.Show("指定的日志文件不存在！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取日志文件时出错：" + ex.Message);
            }
        }

        private void StartWatchingFile()
        {
            string logFilePath = config.log.to; //rootDirectory + "\\frp\\log\\frpslog.log";
            fileWatcher = new FileSystemWatcher();
            fileWatcher.Path = Path.GetDirectoryName(logFilePath);
            fileWatcher.Filter = Path.GetFileName(logFilePath);
            fileWatcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
            fileWatcher.Changed += FileWatcher_Changed;
            fileWatcher.EnableRaisingEvents = true;
        }

        private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            // 同样使用Invoke来更新richTextBox1
            this.richTextBox1.Invoke(new Action(() =>
            {
                ReadAndDisplayLogs();
            }));
        }
    }
}
